package fr.upmc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.upmc.utils.SessionTracker;

public class ValidateAuth extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		//Logout?
		String action = request.getParameter("action");
		if(action != null && action.equals("logout")){
			SessionTracker.eraseSession(request);
			response.sendRedirect("index.html");
			return;
		}

		String name = request.getParameter("name");
		String passwd = request.getParameter("password");
		
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
		
		if(SessionTracker.authenticate(name, passwd, request)){
			RequestDispatcher rd = request.getRequestDispatcher("accueil.jsp");
			
			rd.forward(request, response);
		}
		else{
			response.sendRedirect("index.html?error=bad_login");
		}
		
		pw.close();
		
		return;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		doGet(request,response);
		return;
	}
}
